/**
 * @FileName: ProductOrderService.java
 * @Author
 * @Description:
 * @Date 2016年5月23日 下午5:13:13
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.SystemConfigUtil;
import com.alibaba.fastjson.JSONArray;
import com.jfinal.kit.StrKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

public class IotOrderService {
    private static final Logger      logger       = LoggerFactory.getLogger(IotOrderService.class);
    public static final IotOrderService service      = new IotOrderService();

    public String getSqlSelect(){
        String sql = " select o.*,"
                + InterfaceUtil.getCitySql("o.handler_org_id") + " as city, "
                + InterfaceUtil.getAreaSql("o.handler_org_id") + " as area, "
                + " org.NumCode, org.DisplayName,  (select class_name from organization_class where enabled = '1' and id = org.webSiteId) as sitetype,  "
                + " DATE_FORMAT(o.created_time,'%Y-%m-%d %T') as created_datetime,m.user_name,m.`name` as staff_name,m.emp_code,"
                +" (case o.order_status when 0 then '提交'  when 1 then '参数错误未办理'  when 4 then '预占错误'  when 5 then '已完成' " +
                " when 6 then '失败'  when 7 then '网络超时'  when 8 then '结果解析错误' else '未知' end)as order_state," +
                "(case  when o.cmcc_order_id is not null then  o.cmcc_order_id else sp.order_id  end ) as cmcc_id," +
                "DATE_FORMAT(o.processing_time,'%Y-%m-%d %T') as processing_datetime," +
                "o.processing_desc ";
        return sql;
    }

    public String getSqlFilter(ConcurrentHashMap<String, Object> searchInfo){
        String sqlExceptSelect = " from iot_order o left join member_org m on o.handler_user_id=m.id " +
                " left join organization org on o.handler_org_id=org.id " +
                " left join sales_promotion sp on o.order_id=sp.thirdpart_id where 1=1 ";

        for(Entry<String, Object> item : searchInfo.entrySet()){
            sqlExceptSelect += appendQueryFilter(item);
        }
        sqlExceptSelect += " ORDER BY o.created_time DESC";

        return sqlExceptSelect;
    }

    private Object getOrgLimit(String orgId){
        String sql = " and o.handler_org_id in("
                + InterfaceUtil.getChlidOrgIdSql(Integer.parseInt(orgId), Constant.MAX_ORG_LEVEL, true) + ") ";
        return sql;
    }

    /**
     * @Title: buildQuery
     * @Description:追加查询条件
     */
    private String appendQueryFilter(Entry<String, Object> item){
        StringBuilder sb = new StringBuilder();
        Object valueObj = item.getValue();
        String value = "";
        String key = item.getKey();
        if(null != valueObj){
            value = String.valueOf(valueObj);
        }
        switch(key){
            case "order_id":
                sb.append(getAndLikeFilter("o.order_id", value));
                break;
            case "handle_number":
                sb.append(getAndLikeFilter("o.handle_number", value));
                break;
            case "cmcc_id":
                sb.append(String.format(" AND ( ( %s LIKE '%%%s%%') Or ( %s LIKE '%%%s%%') ) ", "o.cmcc_order_id",
                                        value, "sp.order_id", value));
                break;
            case "staff_name":
                sb.append(getAndLikeFilter("m.name", value));
                break;

            case "order_status":
                if(!value.equals("-1")){
                    sb.append(getOrderStatusFilter(value));
                }
                break;
            case "start_date":
                sb.append(getStartTimeFilter(value));
                break;
            case "end_date":
                sb.append(getEndTimeFilter(value));
                break;
            case "org_id":
                sb.append(getOrgLimit(value));
                break;
            case "order_type":
                sb.append(getAndLikeFilter("o.type", value));
                break;
            default:
                break;
        }
        return sb.toString();
    }

    /**
     * @Title: getPayStatusFilter
     * @Description:TODO
     * @param keyName
     * @param valueJA
     * @return Object
     */
    private Object getPayStatusFilter(String keyName, JSONArray valueJA){
        String sql = "";
        boolean isAll = false;
        for(int i = 0, len = valueJA.size(); i < len; i++){
            String va = (String)valueJA.get(i);
            if(i == 0){
                if(!"-1".equals(va)){
                    sql += " AND (" + keyName + " = " + va;
                } else{
                    isAll = true;
                }
            } else{
                if(!"-1".equals(va)){
                    if(isAll){
                        sql += " AND (" + keyName + " = " + va;
                        isAll = false;
                    } else{
                        sql += " OR " + keyName + " = " + va;
                    }
                }
            }
            if((i == len - 1) && !isAll){
                sql += ")";
            }

        }

        return StrKit.notBlank(sql) ? String.format(sql) : "";
    }

    private String getPayPlatFilter(String value){
        if(value.equals("1")){
            return String.format(" AND o.pay_plat = 14 ");
        } else if(value.equals("3")){
            return String.format(" AND o.pay_plat = 20 ");
        }else{
            return String.format(" AND ((o.pay_plat = 15) OR (o.pay_plat = 16)) ");
        }

    }

    private String getOrderStatusFilter(String value){
        if(value.equals("1")){
            return String.format(" AND o.order_status = 5 ");
        } else{
            return String.format(" AND o.order_status != 5 ");
        }

    }

    // /**
    // * @Title: getCreatorFilter
    // * @Description:获取创建者查询条件
    // */
    // private String getCreatorFilter(String value){
    // return String.format(" AND order_items.product_id IN (SELECT id FROM
    // product WHERE creator=%s) ", value);
    // }
    //
    // /**
    // * @Title: getSubOrgIdFilter
    // * @Description:获取机构和子机构查询条件
    // */
    // private String getSubOrgIdFilter(String value){
    // if(!StrKit.isBlank(value)){
    // return String.format(" AND order_info.org_id IN(%s) ",
    // InterfaceUtil.getChlidOrgIdSql(Integer.parseInt(value),
    // Constant.MAX_ORG_LEVEL, true));
    // }
    // return "";
    // }

    /**
     * @Title: getEndTimeFilter
     * @Description:获取开始时间查询条件
     */
    private String getEndTimeFilter(String value){
        return String.format(" AND o.created_time <= '%s 23:59:59' ", value);
    }

    /**
     * @Title: getStartTimeFilter
     * @Description:获取结束时间查询条件
     */
    private String getStartTimeFilter(String value){
        return String.format(" AND o.created_time >= '%s 00:00:00' ", value);
    }

    /**
     * @Title: getAndLikeFilter
     * @Description:获取KeyName和value模糊查询条件
     */
    private String getAndLikeFilter(String keyName, String value){
        return String.format(" AND %s LIKE '%%%s%%' ", keyName, value);
    }
}
